Page({
  data: {
    countDownVisible: true,
    mobile: '',
    code: '',
    redirect: ''
  },
  countDownChange(ev) {
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0,
    })
  },
  //校验手机号码
  regMobile() {
    const reg = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/
    const valid = reg.test(this.data.mobile.trim())
    if (!valid) wx.utils.toast('请输入正确的手机号码')
    return valid
  },
  //检验验证码
  regCode() {
    const reg = /^\d{6}$/
    const valid = reg.test(this.data.code.trim())
    if (!valid) wx.utils.toast('请输入正确的验证码')
    return valid
  },
  //获取手机验证码
  async getCode() {
    //不合法
    if (!this.regMobile()) return
    //合法，发送请求
    const res = await wx.http.get('/code', { mobile: this.data.mobile })
    this.data.code = res.data.code
    wx.utils.toast('发送验证码成功')
    this.setData({
      countDownVisible: true,
      code: this.data.code
    })
  },
  //复制验证码
  copyCode() {
    wx.setClipboardData({
      data: this.data.code
    })
  },
  onLoad(options) {
    this.setData({ redirect: options.redirect })
  },
  //登录
  async onLogin() {
    //校验手机号码和验证码是否合法
    if (!this.regMobile()) return
    if (!this.regCode()) return
    //发送请求
    const res = await wx.http({
      url: '/login',
      method: 'post',
      data: { mobile: this.data.mobile, code: this.data.code }
    })
    wx.utils.toast('登录成功')
    //把token存储到本地存储和app函数里面
    getApp().setToken(res.data.token, res.data.refreshToken)
    //重定向地址
    const redirect = this.data.redirect || 'pages/my/index'
    //跳转页面
    wx.reLaunch({ url: '/' + redirect })
  }
})
